//
//  KINGMainViewController.swift
//  肉荣微博
//
//  Created by king on 15/7/28.
//  Copyright © 2015年 king. All rights reserved.
//

import UIKit

class KINGMainViewController: UITabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        tabBar.backgroundImage = UIImage(named: "tabbar_background")
        addControllers()
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        setupAddbtn()
    }

    private func addControllers() -> () {
        addController(KINGHomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addController(KINGMessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addController(KINGDiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addController(KINGProfileTableViewController(), title: "我", imageName: "tabbar_profile")
        //print(addBtn)
    }
    
    private func setupAddbtn() {
        let w = UIScreen.mainScreen().bounds.width / CGFloat(viewControllers!.count)
        let rect = CGRectMake(0, 0, w, tabBar.bounds.height)
        addBtn.frame = CGRectOffset(rect, 2 * w, 0)
    }
    //MARK: - 按钮点击事件
    func clickAddBtn () {
        let vc = KINGUserAccount.isLogin ? KINGOAuthViewController() : KINGComposeViewController()
        presentViewController(UINavigationController(rootViewController: vc), animated: true, completion: nil)
        print("点击了按钮")
    }
    
    lazy private var addBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        self.tabBar.addSubview(btn)
        btn.addTarget(self, action: "clickAddBtn", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    
    private func addController(controller:(UIViewController), title:String, imageName:String) -> () {
        tabBar.tintColor = UIColor.orangeColor()
        controller.title = title
        controller.tabBarItem.image = UIImage(named: imageName)
        let nav = UINavigationController(rootViewController: controller)
        addChildViewController(nav)
    }

}
